package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.service.ClothingProductService;
import com.graduation.springbootinit.mapper.OrderMapper;
import com.graduation.springbootinit.mapper.OrderItemMapper;
import com.graduation.springbootinit.model.entity.ShopPart.AddressBook;
import com.graduation.springbootinit.model.entity.ShopPart.ClothingProduct;
import com.graduation.springbootinit.model.entity.ShopPart.Order;
import com.graduation.springbootinit.model.entity.ShopPart.OrderItem;
import com.graduation.springbootinit.model.vo.ShoppingCartItemVO;
import com.graduation.springbootinit.model.vo.OrderDetailVO;
import com.graduation.springbootinit.service.OrderService;
import com.graduation.springbootinit.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ClothingProductService productService;

    @Resource
    private ShoppingCartService cartService;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private AddressBookServiceImpl addressBookService;

    @Resource
    private  ShoppingCartService shoppingCartService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Order> createOrder(Long userId, Long productId, Integer quantity, Long addressId, String size) {
        // 1. 校验商品是否存在
        ClothingProduct product = productService.getById(productId);
        if (product == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setStoreId(product.getStoreId()); // 设置商户ID
        order.setAddressId(addressId);
        order.setStatus(0); // 待付款
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(quantity)));
        order.setOrderNo(generateOrderNo());
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());

        // 3. 保存订单
        orderMapper.insert(order);

        // 4. 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(productId);
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getImageUrl());
        orderItem.setQuantity(quantity);
        orderItem.setSize(size);
        orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)));
        orderItem.setCreatedAt(new Date());
        orderItem.setUpdatedAt(new Date());
        orderItem.setStoreId(product.getStoreId());

        orderItemMapper.insert(orderItem);

        return ResultUtils.success(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Order> createOrderFromCart(Long userId, Long cartId, Long addressId) {
        Long cartId2 = shoppingCartService.getCartId(userId);
        // 1. 获取购物车已选中商品
        List<ShoppingCartItemVO> cartItems = cartService.getSelectedItems(cartId2);
        if (cartItems.isEmpty()) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "未选择商品");
        }

        // 验证所有商品是否来自同一个商户
        Long storeId = cartItems.get(0).getStoreId();
        boolean isSameStore = cartItems.stream()
                .allMatch(item -> item.getStoreId().equals(storeId));
        if (!isSameStore) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "不能同时购买不同商户的商品");
        }

        // 2. 计算总价
        BigDecimal totalAmount = cartItems.stream()
                .map(ShoppingCartItemVO::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setStoreId(storeId); // 设置商户ID
        order.setAddressId(addressId);
        order.setStatus(0);
        order.setTotalAmount(totalAmount);
        order.setOrderNo(generateOrderNo());
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());

        // 4. 保存订单
        orderMapper.insert(order);

        // 5. 创建订单项
        for (ShoppingCartItemVO cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductName(cartItem.getProductName());
            orderItem.setProductImage(cartItem.getProductImage());
            orderItem.setSize(cartItem.getSize());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(cartItem.getTotalPrice());
            orderItem.setCreatedAt(new Date());
            orderItem.setUpdatedAt(new Date());
            orderItem.setStoreId(cartItem.getStoreId());

            orderItemMapper.insert(orderItem);
        }

        // 6. 清除购物车中已下单的商品
        List<Long> itemIds = cartItems.stream()
                .map(ShoppingCartItemVO::getId)
                .collect(Collectors.toList());
        cartService.removeByIds(itemIds);

        return ResultUtils.success(order);
    }

    @Override
    public BaseResponse<Order> getOrderById(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }
        return ResultUtils.success(order);
    }

    @Override
    public BaseResponse<List<Order>> getUserOrders(Long userId, Integer status) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("created_at");

        List<Order> orders = orderMapper.selectList(queryWrapper);
        return ResultUtils.success(orders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> cancelOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }

        // 只有付款的订单可以取消
        if (order.getStatus() != 1) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "订单状态不允许取消");
        }

        // 更新订单状态为已取消
        order.setStatus(4); // 假设4表示已取消
        order.setUpdatedAt(new Date());
        orderMapper.updateById(order);

        // 恢复商品库存
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);

        for (OrderItem item : orderItems) {
            // 增加商品库存
            productService.increaseStock(item.getProductId(), item.getSize(), item.getQuantity());
        }

        return ResultUtils.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> payOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }

        // 只有待付款的订单可以支付
        if (order.getStatus() != 0) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "订单状态不允许支付");
        }

        // 更新订单状态为待发货
        order.setStatus(1); // 1表示待发货
        order.setUpdatedAt(new Date());
        orderMapper.updateById(order);

        return ResultUtils.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> confirmReceive(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }

        // 只有待收货的订单可以确认收货
        if (order.getStatus() != 2) { // 假设2表示待收货
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "订单状态不允许确认收货");
        }

        // 更新订单状态为已完成
        order.setStatus(3); // 假设3表示已完成
        order.setUpdatedAt(new Date());
        orderMapper.updateById(order);

        // 更新商品销量
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);

        for (OrderItem item : orderItems) {
            ClothingProduct product = productService.getById(item.getProductId());
            if (product != null) {
                product.setSalesCount(product.getSalesCount() + item.getQuantity());
                productService.updateById(product);
            }
        }

        return ResultUtils.success(true);
    }

    @Override
    public BaseResponse<OrderDetailVO> getOrderDetail(Long orderId) {
        // 1. 获取订单基本信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }

        // 2. 获取订单项列表
        QueryWrapper<OrderItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(itemQueryWrapper);

        // 3. 获取收货地址

        AddressBook address = addressBookService.getById(order.getAddressId());

        // 4. 组装订单详情
        OrderDetailVO orderDetail = new OrderDetailVO();
        // 复制订单基本信息
        BeanUtils.copyProperties(order, orderDetail);
        // 设置订单项和地址
        orderDetail.setOrderItems(orderItems);
        orderDetail.setAddress(address);

        return ResultUtils.success(orderDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> shipOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
        }

        // 只有待发货的订单可以发货
        if (order.getStatus() != 1) { // 1表示待发货
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "订单状态不允许发货");
        }

        // 获取订单项并扣减库存
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        
        // 检查并扣减所有商品的库存
        for (OrderItem orderItem : orderItems) {
            boolean stockResult = productService.decreaseStock(
                orderItem.getProductId(), 
                orderItem.getSize(), 
                orderItem.getQuantity()
            );
            if (!stockResult) {
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "库存不足，无法发货");
            }
        }

        // 更新订单状态为待收货
        order.setStatus(2); // 2表示待收货
        order.setUpdatedAt(new Date());
        orderMapper.updateById(order);

        return ResultUtils.success(true);
    }

    @Override
    public BaseResponse<List<Order>> getUnshippedOrdersByStore(Long storeId) {
        if (storeId == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "商户ID不能为空");
        }

        // 构建查询条件：商户ID匹配且状态为待发货（status = 1）
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId)
                   .eq("status", 1)  // 1表示待发货状态
                   .orderByAsc("created_at");  // 按创建时间升序排序，优先显示早下的订单

        List<Order> orders = orderMapper.selectList(queryWrapper);
        return ResultUtils.success(orders);
    }

    @Override
    public BaseResponse<List<Order>> getOrdersByStore(Long storeId, Integer status) {
        if (storeId == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "商户ID不能为空");
        }

        // 构建查询条件：商户ID匹配
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        
        // 如果指定了状态，添加状态筛选条件
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 按创建时间降序排序，新订单在前
        queryWrapper.orderByDesc("created_at");

        List<Order> orders = orderMapper.selectList(queryWrapper);
        return ResultUtils.success(orders);
    }

    // ... 其他方法实现

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }

    public static String getOrderStatusDesc(Integer status) {
        switch (status) {
            case 0:
                return "待付款";
            case 1:
                return "待发货";
            case 2:
                return "待收货";
            case 3:
                return "已完成";
            case 4:
                return "已取消";
            case 5:
                return "超时关闭";
            default:
                return "未知状态";
        }
    }
}